package admin

import (
	"context"
	"errors"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserSaveLogic {
	return &UserSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserSaveLogic) UserSave(req *types.UserSaveReq) (resp string, err error) {
	username := &models.User{
		Username: req.Username,
	}
	if utils.GetData(username) {
		if (username.ID != req.Id && req.Id != 0) || req.Id == 0 {
			return "", errors.New("用户名已存在")
		}
	}

	mobile := &models.User{
		Mobile: req.Mobile,
	}
	if utils.GetData(mobile) {
		if (mobile.ID != req.Id && req.Id != 0) || req.Id == 0 {
			return "", errors.New("手机号码已存在")
		}
	}

	data := &models.User{
		Username: req.Username,
		Mobile:   req.Mobile,
		Status:   req.Status,
		Email:    req.Email,
		Avatar:   req.Avatar,
	}

	if req.Id == 0 {
		if req.Password == "" {
			logx.Errorf("密码不能为空: %v", err)
			return "", errors.New("密码不能为空")
		}
		data.Salt = utils.RandStr(6)
		data.Password = utils.MD5(utils.MD5(req.Password) + data.Salt)
		// 创建新角色
		err = utils.InsertData(data)
	} else {
		if req.Password != "" {
			data.Salt = utils.RandStr(6)
			data.Password = utils.MD5(utils.MD5(req.Password) + data.Salt)
		}
		err = utils.UpdateById(req.Id, data)
	}

	if err != nil {
		logx.Errorf("操作用户失败: %v", err)
		return "", err
	}

	return "操作成功", nil
}
